import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { NzMessageService } from 'ng-zorro-antd';
import { Router } from '@angular/router';

@Component({
  selector: 'app-add-match',
  templateUrl: './add-match.component.html',
  styleUrls: ['./add-match.component.less']
})
export class AddMatchComponent implements OnInit {
  validateForm: FormGroup;

  match = {
    home_team: '',
    home_team_logo: '',
    custom_team: '',
    custom_team_logo: '',
    category: '',
    start_time: new Date().getTime(),
    start_day: null,
    start_day_time: null
  };

  constructor(private fb: FormBuilder, private http: HttpClient, private message: NzMessageService, private router: Router) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      start_day     : [ null ,[Validators.required] ],
      home_team    : [ null, [Validators.required] ],
      custom_team    : [ null, [Validators.required] ],
      start_day_time     : [ null ,[Validators.required] ],
      category    : [ null, [Validators.required] ],
      home_team_logo    : [ null, [Validators.required] ],
      custom_team_logo    : [ null, [Validators.required] ],
    });
  }


  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }

    if(!this.validateForm.valid){
      return;
    }

    const day =new Date(this.match.start_day);
    const time = new Date(this.match.start_day_time);
    const combineDate = new Date(day.getFullYear(), day.getMonth(), day.getDate(), time.getHours(), time.getMinutes());
    this.match.start_time = combineDate.getTime();

    this.http.post('/sjb/match', this.match).subscribe((res) => {
      this.message.success('创建赛事成功！');
      this.router.navigate(['/list']);
    }, (err) => {
      this.message.error('创建赛事失败: ' + err);
    });    
  }

}
